The goal of this project is to analyze the complex relationships between economic and population growth, sustainable energy practices, and energy consumption
Author
Affiliation
data detectives - Ayesha, Abhishek, Sheemithra, Toluwanimi, Valerie, Alyssa
School of Information, University of Arizona
Abstract
This project utilizes the comprehensive energy dataset from Our World in Data, spanning from 1900 to 2022, to examine the global energy consumption trends regarding economic growth, population dynamics, and the adoption of sustainable energy practices. The primary goal of the project is to design a predictive dashboard that models a nation’s energy consumption based on essential factors such as population size, GDP, and the proportion of electricity derived from renewable sources. The analysis will utilize a range of statistical and machine learning techniques, including time series decomposition, linear regression for key predictors, and regression analysis. We will evaluate the performance of these regression models using R-squared and Root Mean Squared Error (RMSE) metrics to gauge their accuracy and explanatory power. This evaluation is essential for enhancing predictive accuracy and reliability in energy policy formulation and planning. The project will analyze trends in the use of renewable energy at the regional and national levels, with a certain emphasis on emphasizing countries that lead the way in sustainable energy practices and those making progress toward lower greenhouse gas emissions. This analysis will provide crucial insights for industry and researchers dedicated to promoting energy sustainability and promoting economic growth.
Question 1
Is it possible to predict a nation’s power consumption by considering its population size, gross domestic product (GDP), and the percentage of electricity generated from renewable sources and changes across the years?
Mean Squared Error: 0.0002619234478424262
Mean Squared Error: 2.9373092712492876e-05
Mean Squared Error: 0.0001313336189156297
Mean Squared Error (Multiple Regression): 3.203271840932977e-05
Model: Population vs Energy Consumption
R-squared: 0.35314143440904566
RMSE: 0.016184049179436714
------------------
Model: Gdp vs Energy Consumption
R-squared: 0.9306708673762986
RMSE: 0.0054196948910886925
------------------
Model: Renewables_electricity vs Energy Consumption
R-squared: 0.6549275418223408
RMSE: 0.011460088084985635
------------------
Multiple Regression Model:
R-squared: 0.9273399797855411
RMSE: 0.005659745436795702
Question 2
What countries or regions are engaging in sustainable energy practices and relying more on renewable energy compared to nonrenewable energy? Which countries are moving towards the trajectory of relying more on renewable energy and producing less greenhouse gas emissions?
Data Wrangling for Density Plot
Density plots for renewable and non-renewable energy for the continents
Renewables Consumption Plot
Visualizing the density plots for renewable consumption
Non-renewables consumption Plot
The visualization for the non-renewable consumption of energy
Repo Organization
The following folders comprise the project repository
.github/: This directory is designated for files associated with GitHub, encompassing workflows, actions, and templates tailored for issues.
_extra/: Reserved for miscellaneous files that don’t neatly fit into other project categories, providing a catch-all space for various supplementary documents.
_freeze/: Within this directory lie frozen environment files containing comprehensive information regarding the project’s environment configuration and dependencies.
data/: Specifically allocated for storing i data files crucial for the project’s functionality, encompassing input files, datasets, and other essential data resources.
images/: Serving as a repository for visual assets employed throughout the project, including diagrams, charts, and screenshots, this directory maintains visual elements integral to project documentation and presentation.
.gitignore: This file functions to specify exclusions from version control, ensuring that designated files and directories remain untracked by Git, thus streamlining the versioning process.
README.md: Serving as the primary hub of project information, this README document furnishes essential details encompassing project setup, usage instructions, and an overarching overview of project objectives and scope.
_quarto.yml: Acting as a pivotal configuration file for Quarto, this document encapsulates various settings and options governing the construction and rendering of Quarto documents, facilitating customization and control over document output.
about.qmd: This Quarto Markdown file supplements project documentation by providing additional contextual information, elucidating project purpose, contributor insights, and other pertinent project details.
index.qmd: index.qmd: This serves as the main documentation page for our project. This Quarto Markdown file provides detailed descriptions of our project, including all code and visualization.
Source Code
---title: "Global Energy Trends"subtitle: "INFO 523 - Project Final"author: - name: "data detectives - Ayesha, Abhishek, Sheemithra, Toluwanimi, Valerie, Alyssa" affiliations: - name: "School of Information, University of Arizona"description: "The goal of this project is to analyze the complex relationships between economic and population growth, sustainable energy practices, and energy consumption"format: html: code-tools: true code-overflow: wrap embed-resources: trueeditor: visualexecute: warning: false echo: falsejupyter: python3---## AbstractThis project utilizes the comprehensive energy dataset from Our World in Data, spanning from 1900 to 2022, to examine the global energy consumption trends regarding economic growth, population dynamics, and the adoption of sustainable energy practices. The primary goal of the project is to design a predictive dashboard that models a nation’s energy consumption based on essential factors such as population size, GDP, and the proportion of electricity derived from renewable sources. The analysis will utilize a range of statistical and machine learning techniques, including time series decomposition, linear regression for key predictors, and regression analysis. We will evaluate the performance of these regression models using R-squared and Root Mean Squared Error (RMSE) metrics to gauge their accuracy and explanatory power. This evaluation is essential for enhancing predictive accuracy and reliability in energy policy formulation and planning. The project will analyze trends in the use of renewable energy at the regional and national levels, with a certain emphasis on emphasizing countries that lead the way in sustainable energy practices and those making progress toward lower greenhouse gas emissions. This analysis will provide crucial insights for industry and researchers dedicated to promoting energy sustainability and promoting economic growth.# Question 1Is it possible to predict a nation's power consumption by considering its population size, gross domestic product (GDP), and the percentage of electricity generated from renewable sources and changes across the years?```{python}#| label: question#| echo: false#cell libraryimport pandas as pd# Load the datasetdata = pd.read_csv('data/owid-energy-data.csv')#columns to keepkeep = (['year', 'population', 'gdp', 'electricity_generation', 'primary_energy_consumption', 'renewables_electricity'])#data for q1q1_data = data[keep]# Drop rows with any empty valuesq1_data_cleaned = q1_data.dropna()# Save the cleaned dataset to a new CSV fileq1_data_cleaned.to_csv('data/q1_energy_data_cleaned.csv', index=False)``````{python}#| label: question1#| echo: false# Load the datasetdata = pd.read_csv('data/q1_energy_data_cleaned.csv')# Calculate the percentage of electricity generated from renewable sourcesdata['renewables_percentage'] = (data['renewables_electricity'] / data['electricity_generation']) *100# Standardize or normalize the relevant columns (if needed) # Since the columns are already of type 'double', normalization might be beneficial# Here's an example of Min-Max normalization# You can choose to apply normalization to specific columns as neededcolumns_to_normalize = ['electricity_generation', 'primary_energy_consumption', 'renewables_electricity']for column in columns_to_normalize: data[column] = (data[column] - data[column].min()) / (data[column].max() - data[column].min())# Save the updated dataset to a new CSV filedata.to_csv('data/q1_energy_data_processed.csv', index=False)``````{python}#| label: question2#| echo: falseimport matplotlib.pyplot as pltimport seaborn as sns# Load the datasetdata = pd.read_csv('data/q1_energy_data_processed.csv')plt.figure(figsize=(10, 8))sns.histplot(data['primary_energy_consumption'], kde=True)plt.title('Distribution of Target Variable "primary_energy_consumption"')plt.xlabel('Primary Energy Consumption')plt.ylabel('Frequency')plt.xlim(0, 0.065) # Set x-axis limitsplt.ylim(0, 90) # Set y-axis limitsplt.show()``````{python}#| label: question3#| echo: falseimport matplotlib.pyplot as pltimport seaborn as sns# Load the datasetdata = pd.read_csv('data/q1_energy_data_processed.csv')# Plotting pairplot of relevant columnssns.pairplot(data[['population', 'gdp', 'renewables_electricity', 'primary_energy_consumption']])plt.title('Pairplot of Features and Target Variable')plt.show()# Plotting correlation matrixplt.figure(figsize=(10, 8))sns.heatmap(data[['population', 'gdp', 'renewables_electricity', 'primary_energy_consumption']].corr(), annot=True, cmap='coolwarm', fmt=".2f")plt.title('Correlation Matrix')plt.show()# Plotting scatter plots of features against target variableplt.figure(figsize=(15, 10))# Loop through each feature and plot against the target variablefor i, column inenumerate(['population', 'gdp', 'renewables_electricity']): plt.subplot(2, 2, i+1) sns.scatterplot(x=column, y='primary_energy_consumption', data=data) plt.title(f'Scatter plot of {column} vs Primary Energy Consumption') plt.xlabel(column) plt.ylabel('Primary Energy Consumption')plt.tight_layout()plt.show()``````{python}#| label: question4#| echo: false#| warning: falseimport pandas as pdimport matplotlib.pyplot as plt import statsmodels.api as smfrom statsmodels.tsa.seasonal import seasonal_decomposefrom sklearn.linear_model import LinearRegressionfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import mean_squared_error# Load the datasetq1_energy_data = pd.read_csv('data/q1_energy_data_processed.csv')# Time Series Analysis# Decompose time series data to analyze trends, seasonality, and residualsdecomposition = seasonal_decompose(q1_energy_data['primary_energy_consumption'], model='additive', period=1)decomposition.plot()plt.title('Time Series Decomposition')plt.show()# Regression Analysis# Function to perform linear regression and plot the resultsdef perform_linear_regression(x, y, x_label): x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42) model = LinearRegression() model.fit(x_train.values.reshape(-1, 1), y_train) y_pred = model.predict(x_test.values.reshape(-1, 1)) mse = mean_squared_error(y_test, y_pred) plt.scatter(x_test, y_test, color='blue', label='Actual') plt.plot(x_test, y_pred, color='red', label='Predicted') plt.title(f'Simple Linear Regression: {x_label} vs Primary Energy Consumption') plt.xlabel(x_label) plt.ylabel('Primary Energy Consumption') plt.legend() plt.show()print(f'Mean Squared Error: {mse}')# Perform linear regression for each independent variablefor column in ['population', 'gdp', 'renewables_electricity']: perform_linear_regression(q1_energy_data[column], q1_energy_data['primary_energy_consumption'], column)# Multiple Regression# Combine multiple independent variables and perform regressionX = q1_energy_data[['population', 'gdp', 'renewables_electricity']]y = q1_energy_data['primary_energy_consumption']X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)model = LinearRegression()model.fit(X_train, y_train)y_pred = model.predict(X_test)mse = mean_squared_error(y_test, y_pred)print(f'Mean Squared Error (Multiple Regression): {mse}')##### Line Graphs for Time Series Dataplt.figure(figsize=(15, 10))plt.subplot(2, 2, 1)plt.plot(q1_energy_data['year'], q1_energy_data['primary_energy_consumption'], marker='o', color='blue')plt.title('Primary Energy Consumption Over Time')plt.xlabel('Year')plt.ylabel('Primary Energy Consumption')plt.subplot(2, 2, 2)plt.plot(q1_energy_data['year'], q1_energy_data['population'], marker='o', color='green')plt.title('Population Growth Over Time')plt.xlabel('Year')plt.ylabel('Population')plt.subplot(2, 2, 3)plt.plot(q1_energy_data['year'], q1_energy_data['gdp'], marker='o', color='red')plt.title('GDP Over Time')plt.xlabel('Year')plt.ylabel('GDP')plt.subplot(2, 2, 4)plt.plot(q1_energy_data['year'], q1_energy_data['renewables_electricity'], marker='o', color='orange')plt.title('Renewable Electricity Over Time')plt.xlabel('Year')plt.ylabel('Renewable Electricity')plt.tight_layout()plt.show()# Scatterplotsplt.figure(figsize=(15, 5))plt.subplot(1, 3, 1)plt.scatter(q1_energy_data['population'], q1_energy_data['primary_energy_consumption'], color='blue')plt.title('Population vs Energy Consumption')plt.xlabel('Population')plt.ylabel('Primary Energy Consumption')plt.subplot(1, 3, 2)plt.scatter(q1_energy_data['gdp'], q1_energy_data['primary_energy_consumption'], color='green')plt.title('GDP vs Energy Consumption')plt.xlabel('GDP')plt.ylabel('Primary Energy Consumption')plt.subplot(1, 3, 3)plt.scatter(q1_energy_data['renewables_electricity'], q1_energy_data['primary_energy_consumption'], color='red')plt.title('Renewable Electricity vs Energy Consumption')plt.xlabel('Renewable Electricity')plt.ylabel('Primary Energy Consumption')plt.tight_layout()plt.show()# Model Evaluation# Metrics for Simple Linear Regression# R-squared and RMSEdef evaluate_model(true, pred): r_squared = sm.OLS(true, pred).fit().rsquared rmse = mean_squared_error(true, pred, squared=False)return r_squared, rmse# Evaluate each simple linear regression modelfor column in ['population', 'gdp', 'renewables_electricity']: X = q1_energy_data[column].values.reshape(-1, 1) y = q1_energy_data['primary_energy_consumption'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) model = LinearRegression() model.fit(X_train, y_train) y_pred = model.predict(X_test) r_squared, rmse = evaluate_model(y_test, y_pred)print(f'Model: {column.capitalize()} vs Energy Consumption')print(f'R-squared: {r_squared}')print(f'RMSE: {rmse}')print('------------------')# Metrics for Multiple RegressionX = q1_energy_data[['population', 'gdp', 'renewables_electricity']]y = q1_energy_data['primary_energy_consumption']X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)model = LinearRegression()model.fit(X_train, y_train)y_pred = model.predict(X_test)r_squared, rmse = evaluate_model(y_test, y_pred)print('Multiple Regression Model:')print(f'R-squared: {r_squared}')print(f'RMSE: {rmse}')```# Question 2What countries or regions are engaging in sustainable energy practices and relying more on renewable energy compared to nonrenewable energy? Which countries are moving towards the trajectory of relying more on renewable energy and producing less greenhouse gas emissions?```{python}#| label: MAP1#| echo: false#| warning: falseimport pandas as pdimport plotly.express as pximport geopandas as gpd# Load the datadata = pd.read_csv('data/owid-energy-data.csv')# Load world shapefile for mappingworld = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))# Merge world shapefile with energy dataworld = world.merge(data, how='left', left_on='iso_a3', right_on='iso_code')# Ensure data is filtered from 2000 to 2023world = world[(world['year'] >=2000) & (world['year'] <=2023)]# Calculate the share of renewable energy consumptionworld['renewables_share'] = world['renewables_electricity'] / world['electricity_generation']# Plot the animated mapfig = px.choropleth(world, locations='iso_a3', color='renewables_share', hover_name='name', animation_frame='year', range_color=(0, 1), projection='natural earth', color_continuous_scale=px.colors.sequential.Plasma, title='Share of Renewable Energy Consumption (%)')fig.show()``````{python}#| label: MAP2#| echo: false#| warning: falseimport pandas as pdimport geopandas as gpd# Load the datadata = pd.read_csv('data/owid-energy-data.csv')# Load world shapefile for mappingworld = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))# Merge world shapefile with energy dataworld = world.merge(data, how='left', left_on='iso_a3', right_on='iso_code')# Ensure data is filtered from 2000 to 2023world = world[(world['year'] >=2000) & (world['year'] <=2023)]# Calculate the share of renewable energy consumptionworld['renewables_share'] = world['renewables_electricity'] / world['electricity_generation']# Define color palettecolorscale = [ (0, "purple"), (0.5, "white"), (1, "green") ]# Plot the animated mapfig = px.choropleth(world, locations='iso_a3', color='renewables_share', hover_name='name', animation_frame='year', range_color=(0, 1), projection='natural earth', color_continuous_scale=colorscale, title='Share of Renewable Energy Consumption (%)')fig.show()``````{python}# Create renewable energy dataset as a subset of the datawind_data = data[['country', 'year', 'wind_consumption']]solar_data = data[['country', 'year', 'solar_consumption']]hydro_data = data[['country', 'year', 'hydro_consumption']]# remove all missing valueswind_data_clean = wind_data.dropna()solar_data_clean = solar_data.dropna()hydro_data_clean = hydro_data.dropna()# Group the data by year and sum the wind consumption for each year across all countriesgrouped_wind_data = wind_data_clean.groupby('year')['wind_consumption'].sum()grouped_solar_data = solar_data_clean.groupby('year')['solar_consumption'].sum()grouped_hydro_data = hydro_data_clean.groupby('year')['hydro_consumption'].sum()# Plot each energy type with appropriate labels and colorsplt.figure(figsize=(12, 10))plt.plot(grouped_wind_data.index, grouped_wind_data.values, marker='o', color='skyblue', label='Wind')plt.plot(grouped_solar_data.index, grouped_solar_data.values, marker='o', color='goldenrod', label='Solar')plt.plot(grouped_hydro_data.index, grouped_hydro_data.values, marker='o', color='seagreen', label='Hydro')plt.xlabel('Year')plt.ylabel('Energy Consumption (in terawatt-hours)') plt.title('Global Renewable Energy Consumption') plt.grid(True)plt.legend() # Add a legend to differentiate the linesplt.tight_layout() # Adjust the plot to ensure everything fits without overlapplt.show()``````{python}import matplotlib.pyplot as plt``````{python}``````{python}import matplotlib.dates as mdates# Create electriciy dataset as a subset of the dataelectricity_data = data[['country', 'year', 'greenhouse_gas_emissions']]# remove all missing valueselectricity_data_clean = electricity_data.dropna()# Convert 'year' to datetime for better handling in matplotlibelectricity_data_clean['year'] = pd.to_datetime(electricity_data_clean['year'], format='%Y')# Sorting the dataelectricity_data_clean.sort_values('year', inplace =True)# Trend plotplt.figure(figsize=(10, 6))plt.fill_between(electricity_data_clean['year'], electricity_data_clean['greenhouse_gas_emissions'], color="skyblue", alpha=0.4)plt.plot(electricity_data_clean['year'], electricity_data_clean['greenhouse_gas_emissions'], marker='o', color='skyblue')plt.gcf().autofmt_xdate() # Automatic rotation of the datesmyFmt = mdates.DateFormatter('%Y')plt.gca().xaxis.set_major_formatter(myFmt)plt.xlabel('Year')plt.ylabel('Emissions from Electricity generation (in megatonnes of CO2 equivalents)')plt.title('Trend of Global Greenhouse Gas Emissions from Electricity Generation')plt.grid(True)plt.tight_layout()plt.show()```### Data Wrangling for Density PlotDensity plots for renewable and non-renewable energy for the continents```{python}#| label: data_wrang_density#| message: false#| warning: false## loading the data setimport pandas as pdenergy = pd.read_csv('data/owid-energy-data.csv') ## performing data wrangling operations on the data set to make it suitable for the analysis## selecting the necessary columns for this analysisenergy2 = energy[['year','country','iso_code', 'biofuel_consumption', 'coal_consumption', 'fossil_fuel_consumption', 'gas_consumption', 'hydro_consumption', 'nuclear_consumption', 'oil_consumption', 'other_renewable_consumption', 'renewables_consumption', 'solar_consumption', 'wind_consumption']]### removing the rows with only missing values in it with the exception of the year columnenergy2_cleaned = energy2.dropna(subset = energy2.columns.difference(['year']), how ='all')### we remove the rows in the country column that are not countries but rather regions or continents### loading the data set for the country codecountry_codes = pd.read_csv('data/country_codes.csv')# filtering the energy data set by removing regions which are not countries from the country column in the data set## first we select the valid country codesvalid_country_codes =set(country_codes['Alpha-3 code'])## filtering the country column in the data setenergy_filtered = energy2_cleaned[energy2_cleaned['iso_code'].isin(valid_country_codes)]###removing all rows with NA values except the iso_codes, year and country columns in the data setenergy_wrangled = energy_filtered.dropna(subset = energy_filtered.columns.difference(['year', 'iso_code', 'country']), how ='all')### removing the values with na values in the data setenergy_wrangled = energy_wrangled.fillna(0)# Select columns to check for 0 valuescolumns_to_check = energy_wrangled.columns.difference(['year', 'iso_code', 'country'])# Filter rows with 0 values in all columns except 'year', 'country', and 'iso_code'energy_wrangled = energy_wrangled[(energy_wrangled[columns_to_check] !=0).any(axis =1)]### The next step is feature engineering where new columns in the data set are created## note that there is a column for the renewable energy consumption total### creating a column for the total consumption of non-renewable energyenergy_wrangled['non_renewables_consumption'] = energy_wrangled['coal_consumption'] + energy_wrangled['fossil_fuel_consumption'] + energy_wrangled['gas_consumption'] + energy_wrangled['nuclear_consumption'] + energy_wrangled['oil_consumption']### rounding the rows in the newly column to 3 decimal placesenergy_wrangled['non_renewables_consumption'] = energy_wrangled['non_renewables_consumption'].round(3)### a new column for the total consumption is created energy_wrangled['total_consumption'] = energy_wrangled['non_renewables_consumption'] + energy_wrangled['renewables_consumption']#### making sure that the total consumption is in two decimal places energy_wrangled['total_consumption'] = energy_wrangled['total_consumption'].round(3)### the next step is to feature engineer and group the data into continents### generating a function that will group the countries into their respective continentsdef group_countries_by_continent(iso_code): continents = {'Africa': ['DZA', 'AGO', 'BEN', 'BWA', 'BFA', 'BDI', 'CPV', 'CMR', 'CAF', 'TCD', 'COM', 'COG', 'COD', 'DJI', 'EGY', 'GNQ', 'ERI', 'SWZ', 'ETH', 'GAB', 'GMB', 'GHA', 'GIN', 'GNB', 'CIV', 'KEN', 'LSO', 'LBR', 'LBY', 'MDG', 'MWI', 'MLI', 'MRT', 'MUS', 'MAR', 'MOZ', 'NAM', 'NER', 'NGA', 'RWA', 'STP', 'SEN', 'SYC', 'SLE', 'SOM', 'ZAF', 'SSD', 'SDN', 'TZA', 'TGO', 'TUN', 'UGA', 'ZMB', 'ZWE'],'Asia': ['AFG', 'ARM', 'AZE', 'BHR', 'BGD', 'BTN', 'BRN', 'KHM', 'CHN', 'CYP', 'GEO', 'IND', 'IDN', 'IRN', 'IRQ', 'ISR', 'JPN', 'JOR', 'KAZ', 'KWT', 'KGZ', 'LAO', 'LBN', 'MYS', 'MDV', 'MNG', 'MMR', 'NPL', 'PRK', 'OMN', 'PAK', 'PSE', 'PHL', 'QAT', 'SAU', 'SGP', 'KOR', 'LKA', 'SYR', 'TWN', 'TJK', 'THA', 'TLS', 'TKM', 'ARE', 'UZB', 'VNM', 'YEM', 'TUR', 'THA'],'Europe': ['ALB', 'AND', 'AUT', 'BLR', 'BEL', 'BIH', 'BGR', 'HRV', 'CZE', 'DNK', 'EST', 'FIN', 'FRA', 'DEU', 'GRC', 'HUN', 'ISL', 'IRL', 'ITA', 'XKX', 'LVA', 'LIE', 'LTU', 'LUX', 'MLT', 'MDA', 'MCO', 'MNE', 'NLD', 'MKD', 'NOR', 'POL', 'PRT', 'ROU', 'RUS', 'SMR', 'SRB', 'SVK', 'SVN', 'ESP', 'SWE', 'CHE', 'UKR', 'GBR', 'VAT'],'North America': ['ATG', 'BHS', 'BRB', 'BLZ', 'CAN', 'CRI', 'CUB', 'DMA', 'DOM', 'SLV', 'GRL', 'GRD', 'GTM', 'HTI', 'HND', 'JAM', 'MEX', 'NIC', 'PAN', 'PRI', 'KNA', 'LCA', 'VCT', 'TTO', 'USA'],'South America': ['ARG', 'BOL', 'BRA', 'CHL', 'COL', 'ECU', 'FLK', 'GUF', 'GUY', 'PRY', 'PER', 'SUR', 'URY', 'VEN'],'Antarctica': ['ATA'],'Europe': ['ALB', 'AND', 'AUT', 'BLR', 'BEL', 'BIH', 'BGR', 'HRV', 'CZE', 'DNK', 'EST', 'FIN', 'FRA', 'DEU', 'GRC', 'HUN', 'ISL', 'IRL', 'ITA', 'XKX', 'LVA', 'LIE', 'LTU', 'LUX', 'MLT', 'MDA', 'MCO', 'MNE', 'NLD', 'MKD', 'NOR', 'POL', 'PRT', 'ROU', 'RUS', 'SMR', 'SRB', 'SVK', 'SVN', 'ESP', 'SWE', 'CHE', 'UKR', 'GBR', 'VAT'],'Australia': ['AUS', 'NZL', 'PNG', 'FJI', 'SLB', 'VUT', 'NZL'] }for continent, countries in continents.items():if iso_code in countries:return continentreturnNone# Return None if ISO code not found in any continent# Apply the function to create the 'continents' column in energy_wrangled DataFrameenergy_wrangled['continents'] = energy_wrangled['iso_code'].apply(group_countries_by_continent)### removing hong kong since it is not a country from the data setenergy_wrangled = energy_wrangled[energy_wrangled['iso_code'] !='HKG']```### Renewables Consumption PlotVisualizing the density plots for renewable consumption```{python}#| label: density1_redone#| output: falseimport matplotlib.pyplot as pltimport seaborn as snsfrom matplotlib.animation import FuncAnimationfrom matplotlib.ticker import FuncFormatterfrom IPython.display import HTML# Extract unique years from the 'year' columnyears = energy_wrangled['year'].unique()# Function to format the x-axis labels with commasdef format_with_commas(value, pos):return"{:,}".format(int(value))# Function to update the plot for the selected yeardef update_plot(year):# Filter data for the selected year data_year = energy_wrangled[energy_wrangled['year'] == year]# Clear the previous plot plt.clf()# Plot the KDE plot for the selected year sns.kdeplot(data=data_year, x='renewables_consumption', hue='continents', multiple='stack', alpha=0.3, linewidth=0.2)# Set title plt.title(f'Density Plot of Renewables Consumption by Continent for Year {year}')# Set the x label plt.xlabel('Renewable Energy Consumption')# Set the x-axis tick formatter plt.gca().xaxis.set_major_formatter(FuncFormatter(format_with_commas))# Initialize the plot with the first yearupdate_plot(years[0])# Create a FuncAnimation object without controls (slider, play/pause button)ani2 = FuncAnimation(plt.gcf(), update_plot, frames=years, interval=1000)# Convert the animation to HTML formathtml_animation2 = ani2.to_jshtml()``````{python}#| label: hmtl_animation2HTML(html_animation2)```### Non-renewables consumption PlotThe visualization for the non-renewable consumption of energy```{python}#| label: density2_redone#| output: falseimport matplotlib.pyplot as pltimport seaborn as snsfrom matplotlib.animation import FuncAnimationfrom matplotlib.ticker import FuncFormatter# Extract unique years from the 'year' columnyears = energy_wrangled['year'].unique()# Function to format the x-axis labels with commasdef format_with_commas(value, pos):return"{:,}".format(int(value))# Function to update the plot for the selected yeardef update_plot(year):# Filter data for the selected year data_year = energy_wrangled[energy_wrangled['year'] == year]# Clear the previous plot plt.clf()# Plot the KDE plot for the selected year sns.kdeplot(data=data_year, x='non_renewables_consumption', hue='continents', multiple='stack', alpha=0.3, linewidth=0.2)# Set title plt.title(f'Density Plot of Non-Renewables Consumption by Continent for Year {year}')# Set the x label plt.xlabel('Non-Renewable Energy Consumption')# Set the x-axis tick formatter plt.gca().xaxis.set_major_formatter(FuncFormatter(format_with_commas))# Initialize the plot with the first yearupdate_plot(years[0])# Create a FuncAnimation object without controls (slider, play/pause button)ani = FuncAnimation(plt.gcf(), update_plot, frames=years, interval=1000)# Convert the animation to HTML formathtml_animation = ani.to_jshtml()# Display the HTML animationHTML(html_animation)``````{python}#| label: html_animationHTML(html_animation)```# Repo OrganizationThe following folders comprise the project repository- **.github/:** This directory is designated for files associated with GitHub, encompassing workflows, actions, and templates tailored for issues.- **\_extra/:** Reserved for miscellaneous files that don't neatly fit into other project categories, providing a catch-all space for various supplementary documents.- **\_freeze/:** Within this directory lie frozen environment files containing comprehensive information regarding the project's environment configuration and dependencies.- **data/:** Specifically allocated for storing i data files crucial for the project's functionality, encompassing input files, datasets, and other essential data resources.- **images/:** Serving as a repository for visual assets employed throughout the project, including diagrams, charts, and screenshots, this directory maintains visual elements integral to project documentation and presentation.- **.gitignore:** This file functions to specify exclusions from version control, ensuring that designated files and directories remain untracked by Git, thus streamlining the versioning process.- **README.md:** Serving as the primary hub of project information, this README document furnishes essential details encompassing project setup, usage instructions, and an overarching overview of project objectives and scope.- **\_quarto.yml:** Acting as a pivotal configuration file for Quarto, this document encapsulates various settings and options governing the construction and rendering of Quarto documents, facilitating customization and control over document output.- **about.qmd:** This Quarto Markdown file supplements project documentation by providing additional contextual information, elucidating project purpose, contributor insights, and other pertinent project details.- **index.qmd:** index.qmd: This serves as the main documentation page for our project. This Quarto Markdown file provides detailed descriptions of our project, including all code and visualization.